package cn.hbcj.servlet.utils;

import java.sql.DriverManager;

import java.sql.*;

/**
 * 数据库操作工具类
 */
public class DBUtils {

    public final static String URL = "jdbc:mysql://localhost:3306/db_crud";
    public final static String USERNAME = "root";
    public final static String PASSWORD = "root";
    public final static String DRIVER = "com.mysql.jdbc.Driver";

    static {
        try {
            Class.forName(DRIVER);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }

    }

    //定义一个获取数据库连接的方法
    public static Connection getConnection() {
        Connection conn = null;
        try {
            conn = DriverManager.getConnection(URL, USERNAME, PASSWORD);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return conn;
    }

    //关闭数据库连接
    public static void close(ResultSet rs, Statement stat, Connection conn) {
        try {
            if (rs != null) rs.close();
            if (stat != null) stat.close();
            if (conn != null) conn.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }

    }
}
